using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using MVCWeb.Models.ViewData;
using MVCWeb.Models;
using System.IO;

namespace MVCWeb.Controllers
{
    public class NewsController : BaseController
    {
        //
        // GET: /News/
        [Authorize(Roles = "Administrators")]
        public ActionResult Index()
        {
            return View(this.dc.News.OrderByDescending(n => n.PublishedDate).ToList<News>());
        }

        //
        // GET: /News/Create
        [Authorize(Roles = "Administrators")]
        public ActionResult Create()
        {
            NewsNewViewData data = new NewsNewViewData();
            data.News = new MVCWeb.Models.News();
            return View(data);
        } 

        //
        // POST: /News/Create
        [AcceptVerbs(HttpVerbs.Post), Authorize(Roles = "Administrators"), ValidateInput(false)]
        public ActionResult Create(News newsToCreate)
        {
            try
            {
                // TODO: Add insert logic here
                foreach (string file in Request.Files)
                {
                    HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
                    if (hpf.ContentLength == 0)
                        continue;

                    string savePath = @"Uploads\Images\News\";

                    string physicPath = AppDomain.CurrentDomain.BaseDirectory + savePath;
                    if (!Directory.Exists(physicPath))
                    {
                        Directory.CreateDirectory(physicPath);
                    }

                    string sFilename = Path.GetFileName(hpf.FileName);
                    string savedFileName = Path.Combine(physicPath, sFilename);

                    string extension = Path.GetExtension(hpf.FileName).ToLower();

                    int file_append = 0;
                    while (System.IO.File.Exists(Path.Combine(physicPath, sFilename)))
                    {
                        file_append++;
                        sFilename = System.IO.Path.GetFileNameWithoutExtension(hpf.FileName)
                                         + file_append.ToString()
                                         + extension;
                    }

                    savedFileName = Path.Combine(physicPath, sFilename);

                    hpf.SaveAs(savedFileName);

                    newsToCreate.ThumbnailImageUrl = Url.Content("~/" + savePath.Replace('\\', '/') + sFilename);
                }


                newsToCreate.PublishedDate = DateTime.Now;
                newsToCreate.Description = HttpUtility.HtmlEncode(newsToCreate.Description);
                this.dc.News.InsertOnSubmit(newsToCreate);
                this.dc.SubmitChanges();
                return RedirectToAction("Index");
            }
            catch
            {
                NewsNewViewData data = new NewsNewViewData();
                data.News = new MVCWeb.Models.News();
                return View(data);
            }
        }

        //
        // GET: /News/Edit/5
        public ActionResult Edit(int id)
        {
            NewsNewViewData data = new NewsNewViewData();
            data.News = this.dc.News.Single<News>(n => n.NewsId == id);
            return View(data);
        }

        //
        // POST: /News/Edit/5
        [AcceptVerbs(HttpVerbs.Post), Authorize(Roles = "Administrators"), ValidateInput(false)]
        public ActionResult Edit(int id, News newsToEdit)
        {
            try
            {

                foreach (string file in Request.Files)
                {
                    FileInfo oldFile = new FileInfo(Server.MapPath("~/" + newsToEdit.ThumbnailImageUrl));
                    if (oldFile.Exists)
                    {
                        oldFile.Delete();
                    }

                    HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
                    if (hpf.ContentLength == 0)
                        continue;

                    string savePath = @"Uploads\Images\News\";

                    string physicPath = AppDomain.CurrentDomain.BaseDirectory + savePath;
                    if (!Directory.Exists(physicPath))
                    {
                        Directory.CreateDirectory(physicPath);
                    }

                    string sFilename = Path.GetFileName(hpf.FileName);
                    string savedFileName = Path.Combine(physicPath, sFilename);

                    string extension = Path.GetExtension(hpf.FileName).ToLower();

                    int file_append = 0;
                    while (System.IO.File.Exists(Path.Combine(physicPath, sFilename)))
                    {
                        file_append++;
                        sFilename = System.IO.Path.GetFileNameWithoutExtension(hpf.FileName)
                                         + file_append.ToString()
                                         + extension;
                    }

                    savedFileName = Path.Combine(physicPath, sFilename);

                    hpf.SaveAs(savedFileName);

                    newsToEdit.ThumbnailImageUrl = Url.Content("~/" + savePath.Replace('\\', '/') + sFilename);
                }
                newsToEdit = dc.News.Single<News>(n => n.NewsId == id);
                newsToEdit.Description = HttpUtility.HtmlEncode(newsToEdit.Description);
                UpdateModel<News>(newsToEdit);
                dc.SubmitChanges();
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // POST: /News/Delete/5
        [AcceptVerbs(HttpVerbs.Post), Authorize(Roles = "Administrators")]
        public ActionResult Delete(int id)
        {
            try
            {                
                News news = dc.News.Single<News>(x => x.NewsId == id);
                FileInfo oldFile = new FileInfo(Server.MapPath("~/" + news.ThumbnailImageUrl));
                if (oldFile.Exists)
                {
                    oldFile.Delete();
                }
                dc.News.DeleteOnSubmit(news);
                dc.SubmitChanges();
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
